#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_TASKS 100

typedef struct
{
    int total_cpu;        // 总 CPU 时间
    int total_memory;     // 总内存
    int available_cpu;    // 可用 CPU 时间
    int available_memory; // 可用内存
    pthread_mutex_t lock; // 互斥锁
} ResourcePool;

typedef struct
{
    int task_id;          // 任务 ID
    int cpu_needed;       // 所需 CPU 时间
    int memory_needed;    // 所需内存
} Task;

// 模拟资源池
ResourcePool resource_pool;

// 初始化资源池
void init_resource_pool(int cpu, int memory)
{
    resource_pool.total_cpu = cpu;
    resource_pool.total_memory = memory;
    resource_pool.available_cpu = cpu;
    resource_pool.available_memory = memory;
    pthread_mutex_init(&resource_pool.lock, NULL);
}

// 分配资源
int allocate_resources(Task *task)
{
    pthread_mutex_lock(&resource_pool.lock);

    if (task->cpu_needed <= resource_pool.available_cpu &&
        task->memory_needed <= resource_pool.available_memory)
    {
        resource_pool.available_cpu -= task->cpu_needed;
        resource_pool.available_memory -= task->memory_needed;
        pthread_mutex_unlock(&resource_pool.lock);
        return 1; // 分配成功
    }
    else
    {
        pthread_mutex_unlock(&resource_pool.lock);
        return 0; // 分配失败
    }
}

// 释放资源
void release_resources(Task *task)
{
    pthread_mutex_lock(&resource_pool.lock);
    resource_pool.available_cpu += task->cpu_needed;
    resource_pool.available_memory += task->memory_needed;
    pthread_mutex_unlock(&resource_pool.lock);
}

// 模拟任务执行
void *task_execution(void *arg)
{
    Task *task = (Task *) arg;

    printf("Task %d is waiting for resources...\n", task->task_id);

    while (!allocate_resources(task))
    {
        // 等待资源
    }

    printf("Task %d is running...\n", task->task_id);
    // 模拟任务运行
    sleep(2);

    // 释放资源
    release_resources(task);
    printf("Task %d has finished and released resources.\n", task->task_id);

    free(task); // 释放任务内存
    return NULL;
}

int main()
{
    init_resource_pool(10, 20); // 初始化资源池，10 CPU 时间，20 内存

    pthread_t threads[MAX_TASKS];
    for (int i = 0; i < 5; i++)
    {
        Task *task = (Task *) malloc(sizeof(Task));
        task->task_id = i;
        task->cpu_needed = 2 + i;   // 每个任务需要的 CPU
        task->memory_needed = 4 + i; // 每个任务需要的内存

        pthread_create(&threads[i], NULL, task_execution, (void *) task);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(threads[i], NULL);
    }

    return 0;
}
